package util

import (
	"encoding/json"
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/client_core/config"
	"github.com/chicken-team-outside/chicken_transmission/driver"
	"github.com/chicken-team-outside/chicken_transmission/driver/adaptor/local_driver"
	"github.com/chicken-team-outside/chicken_transmission/driver/adaptor/smba_driver"
	"github.com/chicken-team-outside/chicken_transmission/model"
	"os"
)

func createSmbDriver(info json.RawMessage) (driver.LocalDriver, error) {
	auth := new(smba_driver.SmbAuthInfo)
	err := json.Unmarshal(info, auth)
	if err != nil {
		return nil, err
	}
	return smba_driver.Create(*auth)
}

func createLocalDriver(info json.RawMessage) (driver.LocalDriver, error) {
	path := new(string)
	err := json.Unmarshal(info, path)
	if err != nil {
		return nil, err
	}
	if stat, err := os.Stat(*path); err != nil {
		return nil, err
	} else if !stat.IsDir() {
		return nil, fmt.Errorf("path is not a directory")
	}
	dr := local_driver.NewLocalDriver(*path)
	return dr, nil
}

func CreateLocalDriver(info *config.DriverInfo) (driver.LocalDriver, error) {
	switch info.Vendor {
	case model.Vendor_SMB2:
		return createSmbDriver(info.ConnectionInfo)
	case model.Vendor_Local:
		return createLocalDriver(info.ConnectionInfo)
	default:
		return nil, fmt.Errorf("unsupported vendor: %v", info.Vendor)
	}
}
